package com.zkc.zblog.controller;

import com.baomidou.mybatisplus.extension.api.ApiController;
import com.zkc.zblog.entity.ZblogUser;
import com.zkc.zblog.exception.ErrorCode;
import com.zkc.zblog.exception.KeyCode;
import com.zkc.zblog.md5.DigestUtil;
import com.zkc.zblog.redis.RedisUtils;
import com.zkc.zblog.service.ZblogUserService;
import com.zkc.zblog.utils.Dto;
import com.zkc.zblog.utils.DtoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/zblogUser")
@Api(description = "后台用户的操作接口")
public class ZblogUserController extends ApiController {

    @Resource
    private ZblogUserService zblogUserService;

    @Resource
    RedisUtils redisUtils;

    /**
     * 后台用户的登陆接口
     */
    @ApiOperation(value = "后台用户的登陆接口")
    @PostMapping("/admin")
    public Dto login(@ApiParam(value = "用户账号") @RequestParam("ucode") String ucode, @ApiParam(value = "密码") @RequestParam("upassword") String upassword, @ApiParam(value = "验证码") @RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response) {

        //验证码判断
        Cookie cookies[] = request.getCookies();
        String cookieValue = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (KeyCode.VERIFY_ID.equals(cookies[i].getName())) {
                    cookieValue = cookies[i].getValue();
                    break;
                }
            }
        }

        if (StringUtils.isEmpty(code)) {
            return DtoUtil.returnFail("验证码为空 !", ErrorCode.BIZ_HOTEL_QUERY_HOTEL_FEATURE_FAIL);   //验证码为空
        } else if (!redisUtils.exist(cookieValue)) {
            return DtoUtil.returnFail("验证码失效!", ErrorCode.BIZ_GET_VIDEO_DESC_FAIL);   //验证码已失效
        } else if (!redisUtils.get(cookieValue).equals(code)) {
            return DtoUtil.returnFail("验证码错误!", ErrorCode.BIZ_HOTEL_QUERY_TRADE_AREA_FAIL);   //验证码错误
        }
        if (StringUtils.isEmpty(upassword)) {
            return DtoUtil.returnFail("密码为空!", ErrorCode.BIZ_QUERY_HOTEL_DETAILS_PASSWORD);   //密码为空
        }

        /*
        使用Shiro 编写认证操作
        */
        //1、获取Subject
        Subject subject = SecurityUtils.getSubject();
        //2、分装用户数据;
        UsernamePasswordToken token = new UsernamePasswordToken(ucode, DigestUtil.hmacSign(upassword));
        try {
            subject.login(token);
            return DtoUtil.returnSuccess(ErrorCode.BIZ_HOTEL_QUERY_HOTCITY_FAIL);  //登录成功
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (!StringUtils.isEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return DtoUtil.returnSuccess(msg);
        }
    }

    /**
     * 后台用户注册账号时发送邮箱验证接口
     */
    @ApiOperation(value = "后台用户注册账号时发送邮箱验证接口", notes = "发送邮箱验证码")
    @PostMapping("/registered")
    public Dto emailregistered(@ApiParam(value = "用户账号,也就是邮箱") @RequestParam("ucode") String ucode) {
        String redis = null;
        try {
            redis = zblogUserService.registered(ucode);
        } catch (Exception e) {
            return DtoUtil.returnSuccess(e.getMessage());
        }
        return DtoUtil.returnDataSuccess(redis);
    }

    /**
     * 后台用户的注册接口
     */
    @ApiOperation(value = "后台用户的注册接口")
    @PostMapping("/registeredcode")
    public Dto registeredcode(@ApiParam(value = "用户名") @RequestParam("uname") String uname, @ApiParam(value = "用户账号") @RequestParam("ucode") String ucode, @ApiParam(value = "密码") @RequestParam("upassword") String upassword, @ApiParam(value = "用户输入的验证码") @RequestParam("code") String code, @ApiParam(value = "redis中验证码的key") @RequestParam("token") String token) {
        try {
            zblogUserService.registeredcode(uname, ucode, upassword, code, token);
        } catch (Exception e) {
            return DtoUtil.returnSuccess(e.getMessage());
        }
        return DtoUtil.returnSuccess("注册成功");
    }

    /**
     * 后台用户全部查询接口
     */
    @ApiOperation(value = "后台用户全部查询接口", notes = "使用mybatisplus分页插件")
    @RequiresPermissions("zblogUser:UserAll")
    @GetMapping("/UserAll")
    public Dto UserAll(@ApiParam(value = "当前页") @RequestParam("current") Integer current, @ApiParam(value = "页大小") @RequestParam("size") Integer size) throws Exception {
        return DtoUtil.returnDataSuccess(zblogUserService.UserALL(current, size));
    }


    /**
     * 后台用户删除接口
     */
    @ApiOperation(value = "后台用户删除接口")
    @DeleteMapping("/UserDelete/{uid}")
    @ResponseBody
    public Dto UserDelete(@ApiParam(value = "用户ID") @PathVariable("uid") Long uid) {

        if (zblogUserService.removeById(uid)) {
            return DtoUtil.returnSuccess("删除成功");
        } else {
            return DtoUtil.returnSuccess("删除失败");
        }
    }

    /**
     * 批量删除用户接口
     */
    @ApiOperation(value = "批量删除用户接口")
    @PostMapping("/UserDeleteList")
    @RequiresPermissions("zblogUser:UserDeleteList")
    public Dto UserDeleteList(@ApiParam("批量删除的分类ID") @RequestBody List<String> uidlist) {
        if (zblogUserService.removeByIds(uidlist)) {
            return DtoUtil.returnSuccess("删除成功");
        } else {
            return DtoUtil.returnSuccess("删除失败");
        }
    }


    /**
     * 后台用户的修改接口
     */
    @ApiOperation(value = "后台用户的修改接口")
    @PutMapping("/UserAllUpdate")
    @ResponseBody
    public Dto UserAllUpdate(@RequestBody ZblogUser zblogUser) {
        if (zblogUserService.updateById(zblogUser)) {
            return DtoUtil.returnSuccess("修改成功");
        } else {
            return DtoUtil.returnSuccess("修改失败");
        }
    }






    /**
     * 后台用户添加接口，类似于注册接口
     */
    @ApiOperation(value = "后台用户添加接口，类似于注册接口")
    @PostMapping("/UserAllAdd")
    @ResponseBody
    public Dto UserAllAdd(@RequestBody ZblogUser zblogUser) {

        /*data 转 string*/
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String datanew = format.format(new Date());
        /*string 转 long*/
        Long yids = Long.parseLong(datanew);
        System.out.println(zblogUser.getUid());
        zblogUser.setYids(yids);
        zblogUser.setUserdata(new Date());
        zblogUser.setUpassword(DigestUtil.hmacSign(zblogUser.getUpassword()));
        if (zblogUserService.UserAdd(zblogUser) == 1) {
            return DtoUtil.returnSuccess("添加成功");
        } else {
            return DtoUtil.returnSuccess("添加失败");
        }
    }

}
